package com.zz.tijian.handle.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisLockUtil {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 尝试获取分布式锁
     *
     * @param lockKey   锁的key
     * @param requestId 请求标识，可以是用户id+服务id等唯一标识
     * @param expire    锁的过期时间，单位秒
     * @return 是否获取锁成功
     */
    public boolean tryLock(String lockKey, String requestId, int expire) {
        Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, expire, TimeUnit.SECONDS);
        return result != null && result;
    }

    /**
     * 释放分布式锁
     *
     * @param lockKey   锁的key
     * @param requestId 请求标识，用于验证释放锁的合法性
     */
    public void releaseLock(String lockKey, String requestId) {
        String currentValue = redisTemplate.opsForValue().get(lockKey);
        if (currentValue != null && currentValue.equals(requestId)) {
            redisTemplate.delete(lockKey);
        }
    }


    public static String generateRequestId(String userId, String serviceId) {
        // 可以使用用户ID + 服务ID + 时间戳（毫秒级别）作为请求标识
        long timestamp = System.currentTimeMillis();
        return userId + "_" + serviceId + "_" + timestamp;
    }
}
